package ltd.jdsoft.cute.spring.base.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import ltd.jdsoft.cute.common.util.ClassNameUtil;
import ltd.jdsoft.cute.spring.base.util.StopWatch;

@Aspect
@Component
public class SlowQueryMonitor {

  private static Logger logger = LoggerFactory.getLogger(SlowQueryMonitor.class);

  // 慢查的阈值,默认500毫秒
  @Value("${slow.query.thresold:500}")
  private long slowThresold;

  @Around("execution(public * ltd.jdsoft..controller..*(..)) or execution(public * ltd.jdsoft..service..*(..))")
  public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
    StopWatch watch = new StopWatch();
    watch.start();

    try {
      return joinPoint.proceed();
    } finally {
      watch.stop();
      prettyLogging(watch, joinPoint);
    }
  }

  private void prettyLogging(StopWatch watch, ProceedingJoinPoint joinPoint) {
    if (watch.getDuration() <= slowThresold) {
      return;
    }
    String className = ClassNameUtil.getShortName(joinPoint.getTarget().getClass());
    // 慢查只记录方法级别，不是方法的不进行记录
    if (!(joinPoint.getSignature() instanceof MethodSignature)) {
      return;
    }
    MethodSignature method = (MethodSignature) joinPoint.getSignature();
    String methodName = method.getMethod().getName();
    logger.warn("{}.{} occurs slow query, cost time {} mills",
        new Object[] {className, methodName, watch.getDuration()});
  }
}
